package com.sbtr.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sbtr.business.publishtask.service.IPublishPredictTaskService;
import com.sbtr.business.publishtask.service.IPublishTaskDataService;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.open.publishtask.dto.*;
import com.sbtr.util.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * <p>
 * 数据类部署任务表 前端控制器
 * </p>
 *

 */
@RestController
@RequestMapping("/publishtask/publish-task-data")
@Api(tags = "部署任务管理（包含模型发布、下线、查询等）")
public class PublishTaskDataController {
	private Logger logger = LoggerFactory.getLogger(PublishTaskDataController.class);

	@Autowired
	private IPublishTaskDataService publishTaskDataService;

	@Autowired
	private IPublishPredictTaskService publishPredictTaskService;

	@Autowired
	private MinioUtil minioUtil;

	private String bucketName="meicloud-ai-platform";


	@ApiOperation(value = "根据id查找", notes = "根据id查找", httpMethod = "GET")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Response<PublishTaskDataDto> findById(@PathVariable("id") Long id) {
		return Response.success(publishTaskDataService.findById(id));
	}

	@ApiOperation(value = "根据id删除", notes = "根据id删除", httpMethod = "DELETE")
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public Response<Boolean> deleteById(@PathVariable("id") Long id) {
		boolean b = publishTaskDataService.deleteById(id);
		if (b) {
			return Response.success("删除成功", b);
		} else {
			throw new RuntimeException("删除失败");
		}
	}

	@ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "GET")
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public Response<PageDto<PublishTaskDataDto>> search(
			@RequestParam(name = "taskName", required = false) String taskName, @RequestParam("page") Long currPage,
			@RequestParam("pageSize") Long pageSize,
			@RequestParam(name = "projectId", required = false) Long projectId) {
		return Response.success(publishTaskDataService.search(taskName, currPage, pageSize, projectId));
	}

//	@ApiOperation(value = "数据预测服务", notes = "数据预测服务", httpMethod = "POST")
//	@RequestMapping(value = "/{id}/predict-data", method = RequestMethod.POST)
//	public Response<List<PredictDataResultDto>> predictData(@PathVariable("id") Long id,
//			@RequestBody PredictDataReqDto reqDto) {
//		try {
//			List<PredictDataResultDto> preddictDataDto = publishTaskDataService.predictData(id, reqDto);
//			return Response.success(preddictDataDto);
//		} catch (Exception e) {
//			e.printStackTrace();
//			JSONObject jsonObject = JSONObject.parseObject(e.getMessage());
//			logger.error(e.getMessage());
//			throw new RuntimeException(jsonObject.getString("message"));
//		}
//	}

	@ApiOperation(value = "数据预测服务", notes = "数据预测服务", httpMethod = "POST")
	@RequestMapping(value = "/{id}/predict-data", method = RequestMethod.POST)
	public Response<List<PredictDataResultDto>> predictData(@PathVariable("id") Long id,
                                                            @RequestBody PredictNewDto reqDto) {
		try {
			List<PredictDataResultDto> preddictDataDto = publishTaskDataService.predictData(id, reqDto);
			return Response.success(preddictDataDto);
		} catch (Exception e) {
			e.printStackTrace();
			JSONObject jsonObject = JSONObject.parseObject(e.getMessage());
			logger.error(e.getMessage());
			throw new RuntimeException(jsonObject.getString("message"));
		}
	}




/*
	@ApiOperation(value = "数据预测服务批量", notes = "数据预测服务批量", httpMethod = "POST")
	@RequestMapping(value = "/{id}/predict-data-multi2", method = RequestMethod.POST)
	public Response<Boolean> predictDataMulti(@PathVariable("id") Long id, @RequestBody PredictDataMultiReqDto req) {
		try {
			if (req.getId() == null) {
				throw new RuntimeException("预测任务id不能为空");
			}
			PublishPredictTaskDto dto = publishPredictTaskService.findById(req.getId());
			if (dto == null) {
				throw new RuntimeException("没有对应任务Id的信息");
			}
			publishTaskDataService.predictDataMulti(id, dto);
			return Response.success(true);
		} catch (Exception e) {
			e.printStackTrace();
			JSONObject jsonObject = JSONObject.parseObject(e.getMessage());
			logger.error(e.getMessage());
			throw new RuntimeException(jsonObject.getString("message"));
		}
	}
*/


	@ApiOperation(value = "数据预测服务批量", notes = "数据预测服务批量", httpMethod = "POST")
	@RequestMapping(value = "/{id}/predict-data-multi", method = RequestMethod.POST)
	public Response<Object> predictDataMulti(@PathVariable("id") Long id,
											  @RequestBody PredictDataMultiNewDto req
	) throws InterruptedException {
			if (req.getId() == null) {
				throw new RuntimeException("预测任务id不能为空");
			}
			PublishPredictTaskDto dto = publishPredictTaskService.findById(req.getId());
			if (dto == null) {
				throw new RuntimeException("没有对应任务Id的信息");
			}

			JSONObject r = publishTaskDataService.predictDataMulti(id, req);
			List<LinkedHashMap<String, String>> list = (List<LinkedHashMap<String, String>>)r.get("list");
			JSONObject o = new JSONObject();
			if(req.getDiagnoseType()==1){
				PageDto<LinkedHashMap<String, String>> pageDto = new PageDto<>();
				pageDto.setPage(req.getPage());
				pageDto.setPageSize(req.getPageSize());
				pageDto.setRowCount(list.size());
				int start = Integer.parseInt(String.valueOf((req.getPage() - 1) * req.getPageSize()));
				int end = Integer.parseInt(String.valueOf((req.getPage() - 1) * req.getPageSize() + req.getPageSize()));
				pageDto.setList(list.subList(start, Math.min(end, list.size())));
				o.put("page",pageDto);
				o.put("rate",r.get("rate"));
				return Response.success(o);
			}else{
				return Response.success(r);
			}

	}





	/*
	@ApiOperation(value = "数据预测服务批量任务创建", notes = "数据预测服务批量任务创建", httpMethod = "POST")
	@RequestMapping(value = "/{id}/predict-data-multi-create", method = RequestMethod.POST)
	public Response<PublishPredictTaskDto> predictDataMultiCreate(@PathVariable("id") Long id,
			@RequestBody PredictDataMultiReqDto req) {
		req.setCreater(UserUtils.getFdLoginName());
		try {
			return Response.success(publishTaskDataService.predictDataMultiCreate(id, req));
		} catch (Exception e) {
			e.printStackTrace();
			JSONObject jsonObject = JSONObject.parseObject(e.getMessage());
			logger.error(e.getMessage());
			throw new RuntimeException(jsonObject.getString("message"));
		}
	}*/


	@ApiOperation(value = "数据预测服务批量任务创建", notes = "数据预测服务批量任务创建", httpMethod = "POST")
	@RequestMapping(value = "/{id}/predict-data-multi-create", method = RequestMethod.POST)
	public Response<PublishPredictTaskDto> predictDataMultiCreate(@PathVariable("id") Long id,
																  @RequestBody PredictDataMultiNewDto req) {
//		req.setCreater(UserUtils.getFdLoginName());
		try {
			return Response.success(publishTaskDataService.predictDataMultiCreate(id, req));
		} catch (Exception e) {
			e.printStackTrace();
			JSONObject jsonObject = JSONObject.parseObject(e.getMessage());
			logger.error(e.getMessage());
			throw new RuntimeException(jsonObject.getString("message"));
		}
	}



	@ApiOperation(value = "根据模型id查找", notes = "根据模型id查找", httpMethod = "GET")
	@RequestMapping(value = "/find-by-model/{modelId}", method = RequestMethod.GET)
	public Response<PublishTaskDataDto> findByModel(@PathVariable("modelId") Long modelId) {
		return Response.success(publishTaskDataService.findByModel(modelId));
	}

	@ApiOperation(value = "服务下线", notes = "服务下线", httpMethod = "POST")
	@RequestMapping(value = "/{id}/stop", method = RequestMethod.POST)
	public Response<Boolean> stopTask(@PathVariable("id") Long id) {
		return Response.success(publishTaskDataService.stopTask(id));
	}

	@ApiOperation(value = "模型发布", notes = "模型发布", httpMethod = "POST")
	@RequestMapping(value = "/publish", method = RequestMethod.POST)
	public Response<Boolean> publishModel(//@Valid
										  @RequestBody PublishTaskDataReqDto req) {
//		if(req.getCreater() == null || req.getCreater().isEmpty()){
//			req.setCreater(UserUtils.getFdLoginName());
//		}
		return publishTaskDataService.publishModel(req);
	}

	@ApiOperation(value = "获取接口使用样例", notes = "获取接口使用样例", httpMethod = "POST")
	@RequestMapping(value = "/{id}/get-predict-json", method = RequestMethod.POST)
	public Response<JSONArray> getPredictJSON(@PathVariable("id") Long id) {
		return Response.success(publishTaskDataService.getPredictJSON(id));
	}

//	@ApiOperation(value = "获取接口预测文本使用模板", notes = "获取接口预测文本使用模板")
//	@RequestMapping(value = "/{id}/get-predict-data-multi-template", method = RequestMethod.GET)
//	public Response<String> getPredictDataMultiTemplate(@PathVariable("id") Long id,
//														@RequestParam(name = "fileType", required = false) String fileType) {
//		return Response.success(publishTaskDataService.getPredictDataMultiTemplate(id, fileType));
//	}

//	@ApiOperation(value = "获取预测任务算法类型", notes = "获取预测任务算法类型")
//	@RequestMapping(value = "/{id}/get-publish-task-type", method = RequestMethod.GET)
//	public Response<String> getPublishTaskType(@PathVariable("id") Long id) {
//		return Response.success(publishTaskDataService.getPublishTaskType(id));
//	}
}
